<?php


namespace App\Http\Controllers\WebApi;


use App\Http\Controllers\WebApi\Business\ConfigBusiness;
use App\Http\Controllers\WebApi\Business\OperationLogsBusiness;
use App\Models\ImGroup;
use App\Models\ImGroupBanned;
use App\Models\ImGroupUser;
use App\Models\ImOperationLogs;
use App\Models\ImUsers;
use App\Validators\GroupValidator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class GroupController
{
    /**
     * 群组列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author an
     * @time 2021-12-14 14:19
     */
    public function groupList(Request $request)
    {
        $param = $request->all();
        list($offset, $limit, $page, $pagesize) = ImGroup::pageProcess();
        $query = ImGroup::with(['groupManager']);
        $calc = ImGroup::selectRaw('count(*) total')->selectRaw('sum( if(OPEN=1,1,0) ) as pubNums')->selectRaw('sum( if(OPEN=2,1,0) ) priNums');
        if (isset($param['searchWord'])) {
            $query->where(function ($sql) use ($param) {
                $sql->where('user_id', $param['searchWord']);//创建者ID
                $sql->orWhere('name', 'like', '%' . $param['searchWord'] . '%');//群名称
                $sql->orWhereHas('groupManager', function ($gmSql) use ($param) {
                    $gmSql->where('nickname', $param['searchWord']);//群组昵称搜索
                });
            });
            $calc->where(function ($sql) use ($param) {
                $sql->where('user_id', $param['searchWord']);//创建者ID
                $sql->orWhere('name', $param['searchWord']);//群名称
                $sql->orWhereHas('groupManager', function ($gmSql) use ($param) {
                    $gmSql->where('nickname', $param['searchWord']);//群组昵称搜索
                });
            });
        }
        //群人数搜索，最小值 minNums, 最大值 maxNums, 区间搜索
        if (isset($param['minNums']) && isset($param['maxNums']) && is_numeric($param['minNums']) && is_numeric($param['maxNums'])) {
            $query->whereBetween('users_count', [$param['minNums'], $param['maxNums']]);
            $calc->whereBetween('users_count', [$param['minNums'], $param['maxNums']]);
        }
        //邀入群，0：不允许，1：允许
        if (isset($param['is_allow']) && is_numeric($param['is_allow'])) {
            $query->where('is_allow', $param['is_allow']);
            $calc->where('is_allow', $param['is_allow']);
        }
        //使用状态：0正常 1禁言中
        if (isset($param['is_all_banned']) && is_numeric($param['is_all_banned'])) {
            $query->where('is_all_banned', $param['is_all_banned']);
            $calc->where('is_all_banned', $param['is_all_banned']);
        }
        $summary = $calc->first();
        $summary->page = $page;
        $summary->pagesize = $pagesize;
        //导出群组
        if (isset($param['export']) && $param['export'] == 1) {
            $data = $query->limit(5000)->get();
            return okBack($data);
        }
        $data = $query->offset($offset)->limit($limit)->orderBy('id', 'desc')->get();
        return okBack($data, [
            'summary' => $summary
        ]);
    }

    /**
     * 添加群组
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author an
     * @time 2021-12-14 14:19
     */
    public function groupAdd(Request $request)
    {
        $param = $request->all();
        $valid = GroupValidator::handle($param, 'groupAdd');
        if (true !== $valid) {
            return errBack($valid->first());
        }
        //验证群主ID
        $user = ImUsers::find($param['userId']);
        if (!$user) {
            return errBack('用户不存在');
        }
        if (!$user->easemob_id) {
            return errBack('无效用户');
        }
        $members = isset($param['members']) ? json_decode($param['members'], true) : [];
        $param['desc'] = $param['desc'] ?? '';
        DB::beginTransaction();
        try {
            //获取服务端分组配置
            $groupConfigs = ConfigBusiness::getServerGroupConfigs();
            $imGroup = new ImGroup();
            $input = [
                'name' => $param['groupName'],
                'desc' => $param['desc'],
                'open' => $groupConfigs['open'],
                'max_count' => $groupConfigs['max_count'],
                'users_count' => count($members) + 1,
                'is_audit' => $groupConfigs['is_audit'],
                'is_allow' => $groupConfigs['is_allow'],
                'member' => $members
            ];
            $res = $imGroup->addGroup($input, $param['userId']);
            if ($res['code'] !== 0) {
                throw new \Exception('failed');
            }
            //添加操作日志
            OperationLogsBusiness::addLog(ImOperationLogs::CREATE, '群组ID:' . $res['id']);
            DB::commit();
            return okBack();
        } catch (\Exception $e) {
            DB::rollBack();
            return errBack('创建失败');
        }
    }

    /**
     * 添加群成员
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author an
     * @time 2021-12-14 14:19
     */
    public function addGroupUsers(Request $request)
    {
        $user_id = $request->post('user_id');
        $im_gid = $request->post('im_gid');
        if ($user_id <= 0 || $im_gid <= 0) {
            return errBack('参数错误');
        }
        $groupUserId = ImGroup::where('im_gid', $im_gid)->value('user_id');
        if (!$groupUserId) {
            return errBack('群信息有误');
        }
        $groupUser = new ImGroupUser();
        $res = $groupUser->addSingleMember([
            'im_gid' => $im_gid,
            'member_id' => $user_id
        ], $groupUserId);
        if ($res['code'] !== 0) {
            return errBack($res['msg']);
        }
        return okBack();
    }

    /**
     * 获取群成员
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author an
     * @time 2021-12-14 14:19
     */
    public function getGroupUsers(Request $request)
    {
        $groupId = $request->get('groupId', 0);
        $nickname = $request->get('nickname', 0);
        if ($groupId <= 0) {
            return errBack('群ID有误');
        }
        $group = ImGroup::find($groupId);
        if (!$group) {
            return errBack('群不存在');
        }
        if (!$group->im_gid) {
            return errBack('无效用户');
        }
        list($offset, $limit, $page, $pagesize) = ImGroupUser::pageProcess();
        $query = ImGroupUser::select('id', 'im_gid', 'user_id', 'role', 'status', 'no_disturb', 'created_at')->with(['group' => function ($q) {
            $q->select('im_gid', 'name', 'description', 'face');
        }])->with(['role' => function ($q) {
            $q->select('id', 'name');
        }])->with(['user' => function ($q) {
            $q->select('id', 'nickname', 'headimg');
        }])->where(['im_gid' => $group->im_gid, 'role' => 3])->whereIn('status', [0, 3]);

        if (!empty($nickname)) {
            $query->whereHas('user', function ($q) use ($nickname) {
                $q->where('nickname', 'like', '%' . $nickname . '%');
            });
        }

        $total = $query->count();
        $list = $query->orderBy('id', 'desc')
            ->limit($limit)
            ->offset($offset)
            ->get();
        return okBack($list, [
            'total' => $total,
            'page' => $page,
            'pagesize' => $pagesize,
        ]);
    }

    /**
     * 移除群成员
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author an
     * @time 2021-12-14 14:20
     */
    public function delGroupUser(Request $request)
    {
        $user_id = $request->post('user_id');
        $im_gid = $request->post('im_gid');
        if ($user_id <= 0 || empty($im_gid)) {
            return errBack();
        }
        $groupUserId = ImGroup::where('im_gid', $im_gid)->value('user_id');
        if (!$groupUserId) {
            return errBack('群信息有误');
        }
        $groupUser = new ImGroupUser();
        $res = $groupUser->delSingleMember([
            'im_gid' => $im_gid,
            'member_id' => $user_id
        ], $groupUserId);
        if ($res['code'] !== 0) {
            return errBack($res['msg']);
        }
        return okBack();
    }

    /**
     * 批量移除群成员
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author an
     * @time 2021-12-15 9:22
     */
    public function delManyGroupUser(Request $request)
    {
        $user_id = $request->post('user_id');
        $user_id = json_decode($user_id, true);
        if (empty($user_id)) {
            return errBack('请选择要移除的用户');
        }
        $im_gid = $request->post('im_gid');
        if (empty($im_gid)) {
            return errBack();
        }
        $groupUserId = ImGroup::where('im_gid', $im_gid)->value('user_id');
        if (!$groupUserId) {
            return errBack('群信息有误');
        }
        $groupUser = new ImGroupUser();
        $res = $groupUser->delManyMember([
            'im_gid' => $im_gid,
            'member_id' => implode(',', $user_id)
        ], $groupUserId);
        if ($res['code'] !== 0) {
            return errBack($res['msg']);
        }
        return okBack();
    }

    /**
     * 发送文本消息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author an
     * @time 2021-12-14 14:20
     */
    public function sendText(Request $request)
    {
        $groupIds = $request->post('groupIds');
        $content = $request->post('content');
        if (empty($content)) {
            return errBack('消息不能为空');
        }
        $groupIds = json_decode($groupIds, true);
        if (!$groupIds) {
            return errBack('请选择要发送的群');
        }
        $groups = ImGroup::whereIn('id', $groupIds)->pluck('im_gid');
        if (empty($groups)) {
            return errBack('找不到群相关信息');
        }
    }

    /**
     * 禁用与解禁
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author an
     * @time 2021-12-14 14:20
     */
    public function setStatus(Request $request)
    {
        $id = $request->post('id');
        $status = $request->post('status');
        if ($id <= 0 || !is_numeric($status)) {
            return errBack();
        }
        $group = ImGroup::find($id);
        $group->is_all_banned = $status;
        $group->save();
        return okBack();
    }

    /**
     * 删除群组
     * @param Request $request
     * @param ImGroup $ImGroupModel
     * @return \Illuminate\Http\JsonResponse
     * @author an
     * @time 2021-12-14 14:20
     */
    public function delGroup(Request $request, ImGroup $ImGroupModel)
    {
        $imGid = $request->post('im_gid');
        $groupInfo = ImGroup::where('im_gid', $imGid)->first();
        if (!$groupInfo) {
            return errBack('群组不存在');
        }
        $userId = $groupInfo->user_id;
        $res = $ImGroupModel->delGroup($imGid, $userId);
        if ($res['code'] == 0) {
            return okBack($res['msg']);
        } else {
            return errBack($res['msg']);
        }
    }

    /**
     * 获取群配置项
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author an
     * @time 2021-12-14 14:20
     */
    public function getConfig(Request $request)
    {
        $id = $request->get('id');
        if ($id <= 0) {
            return errBack();
        }
        $data = ImGroup::select(['name', 'summary', 'description', 'max_count', 'open', 'is_allow'])->find($id);
        return okBack($data);
    }

    /**
     * 保存群配置
     * @param Request $request
     * @param ImGroup $imGroup
     * @return \Illuminate\Http\JsonResponse
     * @author an
     * @time 2021-12-14 14:20
     */
    public function saveConfig(Request $request, ImGroup $imGroup)
    {
        $id = $request->get('id');
        $name = $request->get('name');
        $summary = $request->get('summary');
        $description = $request->get('description');
        $max_count = $request->get('max_count');
        $open = $request->get('open');
        $is_allow = $request->get('is_allow');
        if ($id <= 0 || empty($name) || $max_count <= 0 ||
            !is_numeric($open) || !is_numeric($is_allow)) {
            return errBack();
        }
        $group = ImGroup::find($id);
        if (!$group) {
            return errBack('群不存在');
        }
        try {
            $imGroup->editGroup([
                'im_gid' => $group->im_gid,
                'name' => $name,
                'description' => $description,
                'max_count' => $max_count,
                'is_allow' => $is_allow,
                'summary' => $summary,
                'open' => $open
            ]);
            return okBack();
        } catch (\Exception $e) {
            return errBack('设置失败');
        }
    }

    /**
     * 批量禁言群成员
     * @param Request $request
     * @param ImGroupBanned $ImGroupBannedModel
     * @return \Illuminate\Http\JsonResponse
     * @author an
     * @time 2021-12-14 17:38
     */
    public function addManyBanned(Request $request, ImGroupBanned $ImGroupBannedModel)
    {
        $groupId = $request->post('groupId');
        if ($groupId <= 0) {
            return errBack('群ID有误');
        }
        $member_id = $request->post('member_id');
        $member_id = json_decode($member_id, true);
        if (empty($member_id)) {
            return errBack('请选择禁言用户');
        }
        $timeType = $request->post('timeType');
        if (empty($timeType)) {
            return errBack('请选择禁言时间');
        }
//        5分钟 1小时 1天 7天 30天
        if (!in_array($timeType, ['fiveMin', 'oneHour', 'oneDay', 'sevenDay', 'oneMonth'])) {
            return errBack('时间类型有误');
        }
        $mute_duration = 0;
        switch ($timeType) {
            case 'fiveMin':
                $mute_duration = 5 * 60;
                break;
            case 'oneHour':
                $mute_duration = 60 * 60;
                break;
            case 'oneDay':
                $mute_duration = 60 * 60 * 24;
                break;
            case 'sevenDay':
                $mute_duration = 60 * 60 * 24 * 7;
                break;
            case 'oneMonth':
                $mute_duration = strtotime('+1 month') - time();
                break;
            default:
                break;
        }
        $group = ImGroup::find($groupId);
        if (!$group) {
            return errBack('群不存在');
        }
        try {
            $res = $ImGroupBannedModel->addManyBanned([
                'im_gid' => $group->im_gid,
                'member_id' => implode(',', $member_id),
                'mute_duration' => $mute_duration,
            ], $group->user_id);
            if ($res['code'] === 0) {
                return okBack();
            } else {
                return errBack($res['msg']);
            }
        } catch (\Exception $e) {
            return errBack('设置失败');
        }
    }

    /**
     * 批量解除群成员禁言
     * @param Request $request
     * @param ImGroupBanned $ImGroupBannedModel
     * @return \Illuminate\Http\JsonResponse
     * @author an
     * @time 2021-12-15 12:46
     */
    public function removeManyBanned(Request $request, ImGroupBanned $ImGroupBannedModel)
    {
        $groupId = $request->post('groupId');
        if ($groupId <= 0) {
            return errBack('群ID有误');
        }
        $member_id = $request->post('member_id');
        $member_id = json_decode($member_id, true);
        if (empty($member_id)) {
            return errBack('请选择解除禁言的用户');
        }
        $group = ImGroup::find($groupId);
        if (!$group) {
            return errBack('群不存在');
        }
        try {
            $res = $ImGroupBannedModel->freeManyBanned([
                'im_gid' => $group->im_gid,
                'member_id' => implode(',', $member_id),
            ], $group->user_id);
            if ($res['code'] === 0) {
                return okBack();
            } else {
                return errBack($res['msg']);
            }
        } catch (\Exception $e) {
            return errBack('设置失败' . $e->getMessage());
        }
    }
}
